<template>
  <Select
    v-model="currValue"
    filterable
    remote
    ref="distributor"
    :disabled='disabled'
    :loading="loading"
    clearable
    :label-in-value='isLabelInvalue'
    @on-change="onchange"
    @on-query-change="remote"
    @on-open-change="onOpen">
    <Option v-for="item in distributorList" :value="item.id" :key="item">{{item.label}}</Option>
  </Select>
</template>
<script>
  import { debounce } from '@/util'
  export default {
    props: {
      value: {
        type: [String, Number],
        default: null
      },
      isLabelInvalue: {
        type: Boolean,
        default: false
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        distributorList: [],
        loading: false,
        name: '',
        oTimerDetail: null,
        distributorName: ''
      }
    },
    computed: {
      currValue: {
        get() {
          return this.value
        },
        set(v) {
          this.$emit('input', v || '')
        }
      }
    },
    mounted() {
      this.getDetailData(this.name)
    },
    methods: {
      onchange(val) {
        this.$emit('onchange', val)
      },
      onOpen(isOpen) {
        if (isOpen) this.getDetailData(this.name)
      },
      remote(query='') {
        this.name = query
        this.getDetailData(query)
      },
      getDetailData: debounce(function d(query='') {
        this.loading = true
        this.name = query
        let param = {
          realname: query
        }
        return this.$jsonPost("/distributor_salesman/page", param).then(data => {
          this.loading = false
          this.distributorList = []
          this.distributorList = (data.records || []).map(item => {
            return {
              id: item.salesmanId,
              label: item.realname
            }
          })
        })
      }, 400),
      selectDefault(val) { // 如需默认选中第一项，手动调用该方法
        this.distributorName = val
        this.getDetailData(this.distributorName).then(v => {
          if (!this.distributorName) return
          let item = this.distributorList[0] || {}
          this.$refs.distributor.onOptionClick({
            value: item.id,
            label: item.label,
          })
          this.$emit('onchange', { value: item.id,label: item.label })
        })
      },
    },
  }
</script>